﻿(function (window) {
    //String对象的拓展
    if (typeof String.prototype.trim == 'undefined') {
        String.prototype.trim = function () {
            var str = this,
whitespace = ' \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000';
            for (var i = 0, len = str.length; i < len; i++) {
                if (whitespace.indexOf(str.charAt(i)) == -1) {
                    str = str.substring(i);
                    break;
                }
            }
            for (i = str.length - 1; i >= 0; i--) {
                if (whitespace.indexOf(str.charAt(i)) == -1) {
                    str = str.substring(0, i + 1);
                    break;
                }
            }
            return whitespace.indexOf(str.charAt(0)) == -1 ? str : '';
        }
    }
    if (typeof String.prototype.ltrim == 'undefined') {
        String.prototype.ltrim = function () {
            return this.replace(/(^\s*)/g, "");
        }
    }
    if (typeof String.prototype.rtrim == 'undefined') {
        String.prototype.rtrim = function () {
            return this.replace(/(\s*$)/g, "");
        }
    }
    if (typeof String.prototype.htmlEncode == 'undefined') {
        String.prototype.htmlEncode = function (encodeNewLine) {//encodeNewLine:是否encode换行符
            var s = this;
            s = s.replace(/&/g, '&amp;');
            s = s.replace(/</g, '&lt;');
            s = s.replace(/>/g, '&gt;');
            s = s.replace(/'/g, '&quot;');
            if (encodeNewLine) {
                s = s.replace(/\r\n/g, '<br />');
                s = s.replace(/\r/g, '<br />');
                s = s.replace(/\n/g, '<br />');
            }
            return s;
        }
    }
    if (typeof String.prototype.htmlDecode == 'undefined') {
        String.prototype.htmlDecode = function (decodeNewLine) {//decodeNewLine：是否decode换行符
            var s = this;
            if (decodeNewLine) {
                s = s.replace(/<br\s*\/?>/gi, '\r\n');
            }
            s = s.replace(/&quot;/g, '\'');
            s = s.replace(/&gt;/g, '>');
            s = s.replace(/&lt;/g, '<');
            s = s.replace(/&amp;/g, '&');
            return s;
        }
    }
    if (typeof String.prototype.startsWith == 'undefined') {
        String.prototype.startsWith = function (start, ignoreCase) {//start：欲判断字符， ignoreCase：是否忽略大小写
            var s = this;
            if (ignoreCase) {
                s = s.toLowerCase();
                end = end.toLowerCase();
            }
            if (s.substr(0, start.length) == start)
                return true;
            return false;
        }
    }
    if (typeof String.prototype.endsWith == 'undefined') {
        String.prototype.endsWith = function (end, ignoreCase) {//end：欲判断字符， ignoreCase：是否忽略大小写
            var s = this;
            if (ignoreCase) {
                s = s.toLowerCase();
                end = end.toLowerCase();
            }
            if (s.substr(s.length - end.length) == end)
                return true;
            return false;
        }
    }
    //Array对象的拓展
    if (typeof Array.prototype.clear == 'undefined') {
        Array.prototype.clear = function () {
            this.length = 0;
        }
    }
    if (typeof Array.prototype.insertAt == 'undefined') {
        Array.prototype.insertAt = function (index, value) {
            this.splice(index, 0, value);
        }
    }
    if (typeof Array.prototype.removeAt == 'undefined') {
        Array.prototype.removeAt = function (index) {
            /// <summary>
            ///指定位置移除
            /// </summary>
            /// <param name="index">位置</param>
            this.splice(index, 1);
        }
    }
    if (typeof Array.prototype.remove == 'undefined') {
        Array.prototype.remove = function (value) {
            var index = this.indexOf(value);
            if (index >= 0) {
                this.removeAt(index);
            }
        }
    }
    if (typeof Array.prototype.indexOf == 'undefined') {
        Array.prototype.indexOf = function (obj, start) {
            for (var i = (start || 0), j = this.length; i < j; i++) {
                if (this[i] == obj) { return i; }
            }
            return -1;
        }
    }
    if (typeof Array.prototype.deleteRepeat == 'undefined') {
        Array.prototype.deleteRepeat = function () {
            /// <summary>
            /// 删除数组里的重复项
            /// </summary>
            /// <returns type=""></returns>
            var retArr = [], tempObj = {};
            for (var i = 0, tmpItem; (tmpItem = this[i]) != null; i++) {
                if (!tempObj[tmpItem]) {
                    retArr.push(tmpItem);
                    tempObj[tmpItem] = true;
                }
            }
            return retArr;
        }
    }
    yUtils = {
        selectedRange: function (el) {
            /// <summary>
            /// 选中内容
            /// eg: selectedRange(document.getElementById('123'));
            /// </summary>
            /// <param name="el">需要选中对象</param>
            var body = document.body, range, sel;
            if (document.createRange && window.getSelection) {
                //Range 对象表示文档的连续范围区域，如用户在浏览器窗口中用鼠标拖动选中的区域。
                //selection是对当前激活选中区（即高亮文本）进行操作。
                range = document.createRange();
                sel = window.getSelection();
                sel.removeAllRanges();
                try {
                    range.selectNodeContents(el);
                    sel.addRange(range);
                } catch (e) {
                    range.selectNode(el);
                    sel.addRange(range);
                }
            } else if (body.createTextRange) {
                range = body.createTextRange();
                range.moveToElementText(el);
                range.select();
            }
        },
        delegate: function (client, clientMethod) {
            /// <summary>
            /// JavaScript 委托
            /// </summary>
            /// <param name="client">目标对象</param>
            /// <param name="clientMethod">委托方法</param>
            return function () {
                return clientMethod.apply(client, arguments);
            }
        },
        isString: function (obj) {
            /// <summary>
            ///判断是不是String类型
            /// </summary>
            /// <param name="obj">对象</param>
            /// <returns type="">是不是String类型</returns>
            return (obj != null) && (obj != undefined) && (typeof obj == 'string') && (obj.constructor == String);
        },
        isNumber: function (obj) {
            /// <summary>
            /// 判断是否是数字
            /// </summary>
            /// <param name="obj">对象</param>
            /// <returns type="">是否是数字</returns>
            return (typeof obj == 'number') && (obj.constructor == Number);
        },
        isDate: function (obj) {
            /// <summary>
            /// 判断是否是日期
            /// </summary>
            /// <param name="obj">对象</param>
            /// <returns type="">是否是日期</returns>
            return obj && (typeof obj == 'object') && (obj.constructor == Date);
        },
        isArray: function (obj) {
            /// <summary>
            /// 判断是否是数组
            /// </summary>
            /// <param name="obj">对象</param>
            /// <returns type="">是否是数组</returns>
            return obj && (typeof obj == 'object') && (obj.constructor == Array);
        },
        isObject: function (obj) {
            /// <summary>
            /// 判断是否是对象
            /// </summary>
            /// <param name="obj">对象</param>
            /// <returns type="">是否是对象</returns>
            return obj && (typeof obj == 'object') && (obj.constructor == Object)
        },
    };
    yUtils.string = {
        isNullOrEmpty: function (data) {
            /// <summary>
            /// 判断NULL或者空
            /// 参考：http://www.sitepoint.com/testing-for-empty-values/
            /// </summary>
            /// <param name="data">需要判断数据</param>
            /// <returns type="bool">是否是NULL或者空</returns>
            if (typeof (data) == 'number' || typeof (data) == 'boolean') {
                return false;
            }
            if (typeof (data) == 'undefined' || data == null) {
                return true;
            }
            if (typeof (data.length) != 'undefined') {
                return data.length == 0;
            }
            var count = 0;
            for (var i in data) {
                if (data.hasOwnProperty(i)) {
                    count++;
                }
            }
            return count == 0;
        }
    };
    yUtils.datetime = {
        CONSTANT:
            {
                DEFAULT_FORMAT: 'yyyy-MM-dd hh:mm:ss'
            },
        formart: function (date, format) {
            /// <summary>
            /// 时间格式化
            /// 参考：http://yaniswang.com/frontend/2013/02/16/dateformat-performance/
            /// </summary>
            /// <param name="date"></param>
            /// <param name="format"></param>
            /// <returns type=""></returns>
            if (date instanceof Date) {
                var map = {
                    "M": date.getMonth() + 1, //月份 
                    "d": date.getDate(), //日 
                    "h": date.getHours(), //小时 
                    "m": date.getMinutes(), //分 
                    "s": date.getSeconds(), //秒 
                    "q": Math.floor((date.getMonth() + 3) / 3), //季度 
                    "S": date.getMilliseconds() //毫秒 
                };
                format = format || this.CONSTANT.DEFAULT_FORMAT;
                format = format.replace(/([yMdhmsqS])+/g, function (all, t) {
                    var v = map[t];
                    if (v !== undefined) {
                        if (all.length > 1) {
                            v = '0' + v;
                            v = v.substr(v.length - 2);
                        }
                        return v;
                    }
                    else if (t == 'y') {
                        return (date.getFullYear() + '').substr(4 - all.length);
                    }
                    return all;
                });
                return format;
            }
        },
        now: function (format) {
            /// <summary>
            /// 获取当前时间
            /// </summary>
            /// <param name="format">时间格式化类型，默认：yyyy-MM-dd hh:mm:ss</param>
            /// <returns type="">当前时间</returns>
            return this.formart(new Date(), format);
        }
    };
    yUtils.log = {
        CONSTANT: {
            DIALOG_WITH: 400,
            DIALOG_HIGHT: 200
        },
        add: function (message) {
            /// <summary>
            /// 添加窗口日志信息
            /// </summary>
            /// <param name="message">日志信息</param>
            if (!this.window_ || this.window_.closed) {
                var win = window.open("", null, "width=600,height=200,scrollbars=yes,resizable=yes,status=no,location=no,menubar=no,toolbar=no");
                if (!win) return;
                var doc = win.document;
                doc.write("<html><head><title>Debug Log</title></head>" +
                          "<body></body></html>");
                doc.close();
                this.window_ = win;
            }
            var logLine = this.window_.document.createElement("div");
            message = DateTimeUtils.now() + ": " + message;
            logLine.appendChild(this.window_.document.createTextNode(message));
            this.window_.document.body.appendChild(logLine);
        }
    };
    yUtils.ie = {
        copyTextToClipboard: function (text) {
            /// <summary>
            ///仅支持IE浏览器的复制操作 
            /// </summary>
            /// <param name="text">复制到剪切板内容</param>
            var copyFrom = $('<textarea/>');
            copyFrom.text(text);
            $('body').append(copyFrom);
            copyFrom.select();
            document.execCommand('copy', true);
            copyFrom.remove();
        },
        copyElecToClipboard: function (elecId) {
            /// <summary>
            /// 仅支持IE浏览器的对HTML元素复制到剪切板
            /// </summary>
            /// <param name="elecId">需要复制ID</param>
            var obj = document.getElementById(elecId);
            if (obj) {
                JsUtils.selectedRange(obj);
                document.execCommand('copy', true);
            }
        }
    };
    yUtils.dialog =
    {
        CONSTANT:
          {
              WIDTH: 300,
              HEIGTH: 200
          },
        show: function (url, width, heigth) {
            /// <summary>
            /// 打开窗口
            /// </summary>
            /// <param name="url">链接</param>
            /// <param name="width">宽</param>
            /// <param name="heigth">高</param>
            width = width | this.CONSTANT.WIDTH;
            heigth = heigth | this.CONSTANT.HEIGTH;
            if (document.all)//IE  
            {
                var feature = "width:" + width + ";Height:" + heigth + ";status:no;help:no";
                window.showModalDialog(url, null, feature);
            }
            else {
                var feature = "width=" + width + ",height=" + heigth + ",menubar=no,toolbar=no,location=no,";
                feature += "scrollbars=no,status=no,modal=yes";
                window.open(url, null, feature);
            }
        },
        showModel: function (url, width, heigth) {
            /// <summary>
            /// 打开窗口
            /// </summary>
            /// <param name="url">链接</param>
            /// <param name="width">宽</param>
            /// <param name="heigth">高</param>
            document.body.style.backgroundColor = "#999999";
            document.body.style.filter = 'Alpha(Opacity = 40)';
            this.show(url, width, heigth);
            document.body.style.backgroundColor = '';
            document.body.style.filter = '';
        }
    };
    yUtils.event = {
        add: function (element, type, handler, key) {
            /// <summary>
            /// 为元素绑定事件处理程序
            /// </summary>
            /// <param name="element"></param>
            /// <param name="type"></param>
            /// <param name="handler"></param>
            /// <param name="key"></param>
            /// <returns type=""></returns>
            var key = key || handler;
            if (element[type + key])
                return false;
            if (typeof element.addEventListener != "undefined") {
                element[type + key] = handler;
                element.addEventListener(type, handler, false);
            }
            else {
                element['e' + type + key] = handler;
                element[type + key] = function () {
                    element['e' + type + key](window.event);
                };
                element.attachEvent('on' + type, element[type + key]);
            }
            return true;
        },
        remove: function (element, type, key) {
            /// <summary>
            /// 移除元素事件处理程序
            /// </summary>
            /// <param name="element"></param>
            /// <param name="type"></param>
            /// <param name="key"></param>
            /// <returns type=""></returns>
            if (!element[type + key])
                return false;
            if (typeof element.removeEventListener != "undefined") {
                element.removeEventListener(type, element[type + key], false);
            }
            else {
                element.detachEvent("on" + type, element[type + key]);
                element['e' + type + key] = null;
            }

            element[type + key] = null;
            return true;
        },
    };
    yUtils.class = {
        has: function (element, className) {
            /// <summary>
            /// 检查元素是否包含某个class
            /// </summary>
            /// <param name="element"></param>
            /// <param name="className"></param>
            /// <returns type=""></returns>
            var re = new RegExp("(^|\\s)" + className + "(\\s|$)", "i");
            if (element.className.match(re))
                return true;
            return false;
        },
        add: function (element, className) {
            /// <summary>
            /// 为元素添加一个class
            /// </summary>
            /// <param name="element"></param>
            /// <param name="className"></param>
            var re = new RegExp("(^|\\s)" + className + "(\\s|$)", "gi");
            var eleClass = element.className;
            if (!eleClass.match(re))
                element.className = eleClass + " " + className;
        },
        remove: function (element, className) {
            /// <summary>
            /// 为元素删除一个class
            /// </summary>
            /// <param name="element"></param>
            /// <param name="className"></param>
            var re = new RegExp("(^|\\s)" + className + "(\\s|$)", "gi");
            var eleClass = element.className;
            eleClass = eleClass.replace(re, "");
            if (element.className != eleClass)
                element.className = eleClass;
        },
        toggle: function (element, class1, class2) {
            /// <summary>
            /// 切换元素的class， 如果只传入一个class，则切换这个class的有无；如果传入两个class，则元素删除当前class，替换为另一个
            /// </summary>
            /// <param name="element"></param>
            /// <param name="class1"></param>
            /// <param name="class2"></param>
            if (class2 != undefined) {
                if (ssLib.hasClass(element, class1)) {
                    ssLib.removeClass(element, class1);
                    ssLib.addClass(element, class2);
                } else if (ssLib.hasClass(element, class2)) {
                    ssLib.removeClass(element, class2);
                    ssLib.addClass(element, class1);
                }
            } else {
                if (ssLib.hasClass(element, class1)) {
                    ssLib.removeClass(element, class1);
                } else {
                    ssLib.addClass(element, class1);
                }
            }
        },
    };
    yUtils.listbox = {
        addItem: function (listboxId, key, value) {
            /// <summary>
            /// ListBox 添加
            /// </summary>
            /// <param name="listboxId">ListBox ID</param>
            /// <param name="key">键</param>
            /// <param name="value">值</param>
            var lsbox = document.getElementById(listboxId);
            if (lsbox) {
                var count = this.itemCount(lsbox);
                lsbox.options[count] = new Option(value, key, true, true);
            }
        },
        itemCount: function (listbox) {
            /// <summary>
            /// 获取Listbox Item数量
            /// </summary>
            /// <param name="listbox">listbox</param>
            /// <returns type="">Item数量</returns>
            var count = 0;
            if (listbox) {
                count = listbox.options.length == null ? 0 : listbox.options.length;
            }
            return count;
        },
        isExitItem: function (listboxId, key) {
            /// <summary>
            /// 判断是否存在
            /// </summary>
            /// <param name="listboxId">ListBox ID</param>
            /// <param name="key">键</param>
            /// <returns type="bool">是否选中</returns>
            var lsbox = document.getElementById(listboxId);
            var isSelected = false;
            var count = this.itemCount(lsbox);
            for (var i = 0; i < count; i++) {
                if (lsbox.options[i].value == key) {
                    isSelected = true;
                    break;
                }
            }
            return isSelected;
        },
        removeItem: function (listboxId, key) {
            /// <summary>
            /// 移除一项
            /// </summary>
            /// <param name="listboxId">ListBox ID</param>
            /// <param name="key">键</param>
            var lsbox = document.getElementById(listboxId);
            var count = this.itemCount(lsbox);
            for (var i = 0; i < count; i++) {
                if (lsbox.options[i].value == key) {
                    lsbox.options[i].parentNode.removeChild(lsbox.options[i]);
                }
            }
        }
    };
    yUtils.url = {
        get: function (url, key) {
            /// <summary>
            /// 获取连接参数
            ///<para>适用于：yUtilsTest.html?Name='测试'，一类链接.</para>
            /// </summary>
            /// <param name="url">连接</param>
            /// <param name="key">参数名称</param>
            /// <returns type="">参数值</returns>
            var reg = new RegExp("(^|\\?|&)" + key + "=([^&]*)(\\s|&|$)", "i");
            if (reg.test(url)) {
                return unescape(RegExp.$2.replace(/\+/g, " "));
            }
            return "";
        }
    };
    yUtils.iframe = {
        getDynamicIframe: function (id) {
            /// <summary>
            /// 获取动态iframe
            /// <pare>参考：http://www.zomeoff.com/javascript-how-to-load-dynamic-contents-html-string-json-to-iframe/ </pare>
            /// </summary>
            /// <param name="id">ID</param>
            /// <returns type=""></returns>
            var iframe = document.getElementById(id);
            var iframedoc = iframe.document;
            if (iframe.contentDocument)
                iframedoc = iframe.contentDocument;
            else if (iframe.contentWindow)
                iframedoc = iframe.contentWindow.document;
            return iframedoc;
        }
    }
    window.yUtils = yUtils;
})(window);
